package com.ruicar.afs.cloud.channel.online.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.ruicar.afs.cloud.channel.common.feign.ChannelUseCaseService;
import com.ruicar.afs.cloud.channel.common.until.ChannelConfig;
import com.ruicar.afs.cloud.channel.online.condition.ChannelOnlineCondition;
import com.ruicar.afs.cloud.channel.online.condition.QuotaCondition;
import com.ruicar.afs.cloud.channel.online.entity.ChannelBaseInfoTemp;
import com.ruicar.afs.cloud.channel.online.entity.ChannelQuotaInfoTemp;
import com.ruicar.afs.cloud.channel.online.service.ChannelOnlineService;
import com.ruicar.afs.cloud.channel.online.service.ChannelQuotaInfoService;
import com.ruicar.afs.cloud.channel.online.vo.ChannelBulkEditingQuotaInfoVo;
import com.ruicar.afs.cloud.channel.online.vo.FileStoreVo;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.contract.enums.ProcessStatus;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.ruicar.afs.cloud.channel.online.untils.ChannelOnlineConstants.BUSINESS_TYPE_NEW_CAR;
import static com.ruicar.afs.cloud.channel.online.untils.ChannelOnlineConstants.BUSINESS_TYPE_OLD_CAR;

/**
 * @author: sang jian
 * @date: 2020/8/21 15:51
 * @description:
 */

@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/channelQuota")
@Api(value = "channel_quota_info_temp", description = "额度板块")
public class ChannelQuotaController {

    private final ChannelQuotaInfoService channelQuotaInfoService;
    private final ChannelUseCaseService channelUseCaseService;
    private final ChannelConfig channelConfig;
    private final ChannelOnlineService channelOnlineService;


    @Transactional
    @RequestMapping(value = "/upQuota", method = RequestMethod.POST)
    @ApiOperation(value = "保存数据")
    public IResponse saveAccountInfo(@RequestBody QuotaCondition condition) throws  JsonProcessingException {
        if (condition.getRiskId() == null && condition.getRiskIdOld() == null) {
            return IResponse.fail("提交失败！");
        }
        // 先看下进来的是新车还是二手车
        if (condition.getRiskId() != null) {
            //如果有风控的新车id  就去判断  保证金调整是不是 0 如果是零  直接修改额度表。如果不是就要审核
            if (BigDecimal.ZERO.compareTo(condition.getMarginTune())==0) {
                channelQuotaInfoService.effectQuotaMethod(condition,BUSINESS_TYPE_NEW_CAR);
            } else {
                boolean result = channelQuotaInfoService.QuotaToWorkFlowMethod(condition, BUSINESS_TYPE_NEW_CAR);
                if(!result) return IResponse.fail("该合作商的额度维护已在流程中,请勿重复提交!");
            }
        }
        //下面去判断这次有没有二手车
        if (condition.getRiskIdOld() != null) {
            // 再去判断二手车 保证金调整
            if (BigDecimal.ZERO.compareTo(condition.getMarginTuneOld())==0) {
                channelQuotaInfoService.effectQuotaMethod(condition,BUSINESS_TYPE_OLD_CAR);
            } else {

                boolean result = channelQuotaInfoService.QuotaToWorkFlowMethod(condition, BUSINESS_TYPE_OLD_CAR);
                if(!result) return IResponse.fail("该合作商的额度维护已在流程中,请勿重复提交!");
            }
        }
        return IResponse.success("提交成功");
    }


    @PostMapping(value = "/updateChannelQuota")
    @ApiOperation("额度重算后推送到渠道端")
    public void updateChannelQuota(@RequestBody List<ChannelQuotaInfoTemp> quotaInfoTempList){

        if(quotaInfoTempList.size() > 0){
            for (ChannelQuotaInfoTemp quotaInfoTemp : quotaInfoTempList){
                Long channelId = quotaInfoTemp.getChannelId();
                String businessType = quotaInfoTemp.getBusinessType();
                String quotaType = quotaInfoTemp.getQuotaType();
                ChannelQuotaInfoTemp temp = channelQuotaInfoService.getOne(Wrappers.<ChannelQuotaInfoTemp>query().lambda()
                        .eq(ChannelQuotaInfoTemp::getChannelId, channelId)
                        .eq(ChannelQuotaInfoTemp::getBusinessType, businessType)
                        .eq(ChannelQuotaInfoTemp::getQuotaType, quotaType)
                );
                if(temp != null){
                    //更新剩余额度
                    temp.setSurplusQuota(quotaInfoTemp.getSurplusQuota());
                    //更新占用额度
                    temp.setOccupiedQuota(quotaInfoTemp.getOccupiedQuota());
                    //更新临时额度
                    temp.setTempQuota(quotaInfoTemp.getTempQuota());
                    //更新临时额度时间
                    temp.setValidityTermEnd(quotaInfoTemp.getValidityTermEnd());
                    channelQuotaInfoService.updateById(temp);
                }
            }
        }

    }

    @PostMapping(value = "/recomputeQuota")
    @ApiOperation("额度重算")
    public IResponse recomputeQuota(@RequestBody QuotaCondition condition){

        Map<String, String> headers = new HashMap<String, String>();
        headers.put("clientId", channelConfig.getCaseClientId());
        headers.put("clientSecret", channelConfig.getCaseClientSecret());
        List<ChannelQuotaInfoTemp> quotaInfoTempList = channelUseCaseService.recomputeChannelQuota(condition, headers);
        boolean result = true;
        for (ChannelQuotaInfoTemp quotaInfoTemp : quotaInfoTempList){
            Long channelId = quotaInfoTemp.getChannelId();
            String businessType = quotaInfoTemp.getBusinessType();
            String quotaType = quotaInfoTemp.getQuotaType();

            ChannelQuotaInfoTemp temp = channelQuotaInfoService.getOne(Wrappers.<ChannelQuotaInfoTemp>query().lambda()
                    .eq(ChannelQuotaInfoTemp::getChannelId, channelId)
                    .eq(ChannelQuotaInfoTemp::getBusinessType, businessType)
                    .eq(ChannelQuotaInfoTemp::getQuotaType, quotaType)
            );
            if(temp != null){
                //更新剩余额度
                temp.setSurplusQuota(quotaInfoTemp.getSurplusQuota());
                //更新占用额度
                temp.setOccupiedQuota(quotaInfoTemp.getOccupiedQuota());
                result = channelQuotaInfoService.updateById(temp);
            }
        }
        return result ? IResponse.success(condition.getChannelId()) :  IResponse.fail("重算失败") ;

    }


    @PostMapping(value = "/getByConditionForBulkEditing")
    @ApiOperation(value = "多条件获取合作商额度维护列表")
    public IResponse getByConditionForBulkEditing(@RequestBody ChannelOnlineCondition condition) {
        List<ChannelBulkEditingQuotaInfoVo> channelList = channelOnlineService.getByConditionForBulkEditing(condition);
        return IResponse.success(channelList);
    }


    @PostMapping("/importRegister")
    @ApiOperation(value = "批量修改额度")
    @Transactional(rollbackFor = Exception.class)
    public IResponse importRegister(@RequestParam("file") MultipartFile file) throws IOException {

        if (file.isEmpty()) {
            return IResponse.fail("请上传正确文件").setCode(ProcessStatus.ILLEGAL.getCode()).setMsg("请上传正确文件").setData(JSONUtil.parseArray("[{\"msg\":\"请上传正确文件\"}]"));
        }
        String fileType = FileUtil.extName(file.getOriginalFilename());
        String rightFileType = "csv";
        if (!rightFileType.equals(fileType)) {
            return IResponse.fail("请上传与模板格式一致的csv文件").setCode(ProcessStatus.ILLEGAL.getCode()).setMsg("请上传与模板格式一致的csv文件").setData(JSONUtil.parseArray("[{\"msg\":\"请上传与模板格式一致的csv文件\"}]"));
        }
        try {
            channelQuotaInfoService.handleCsvImport(file);
        } catch (Exception e) {
            log.info(e.getMessage());
            return IResponse.fail(e.getMessage()).setCode(ProcessStatus.ILLEGAL.getCode()).setMsg(e.getMessage()).setData(JSONUtil.parseArray("[{\"msg\":\"" + e.getMessage() + "\"}]"));
        }
        return IResponse.success(FileStoreVo.builder().build());
    }



}
